<?php
declare (strict_types = 1);

namespace app\middleware;

use app\services\JwtService;

class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next,array $role)
    {
        $token=$request->header('Authorization');
        //没有token
        if (!$token){
            return resultSuccess("token是空的");
        }
        //没有找到jwt类
        $jwt=new JwtService();
        try {
            $decode=$jwt->checkToken($token);
        }catch (\Exception $e){
            // echo $e;
            return resultError('位置错误');
        }
        //解析token
        $decode=json_decode(json_encode($decode),true);

        if (!$decode){
            return resultError("token 不合法");
        }
        
        if (time() > $decode['nbf']){
            return resultError("token 已过期");
        }

        if(\in_array($decode['user']['desc'],$role) == false){
            return \resultError('角色错误');
        }

        $request->withMiddleware(['user' => $decode['user'],'token'=>$token]);
        return $next($request);
    }

}
